﻿
//定义相关接口参数
// 非对称算法
var ALGID_AUTO = 0;							// 使用证书时自动适配
var ALGID_RSA1024 = 1;						// RSA 1024位算法
var ALGID_RSA2048 = 2;						// RSA 2048位算法
var ALGID_ECC = 3;							// SM2 256位算法

// 摘要算法
var ALGID_HASH_SHA1 = 1;					//SHA-1算法
var ALGID_HASH_SHA256 = 2;  				//SHA-256算法
var ALGID_HASH_SHA512 = 3;  				//SHA-512算法
var ALGID_HASH_MD5 = 4;     				//MD5算法
var ALGID_HASH_MD4 = 5; 					//MD4算法
var ALGID_HASH_SM3 = 6;						//SM3算法

// 证书类型定义
var ENCRYPT_TYPE = 1;						//加密证书
var SIGN_TYPE = 2;							//签名证书

// 证书基本项
var X509_CERT_VERSION =	1;					// 证书版本
var X509_CERT_SERIAL =	2;					// 证书序列号
var X509_CERT_SIGNALG =	3;					// 证书签名算法标识
var X509_CERT_ISSUER_C = 4;					// 证书颁发者国家(C)
var X509_CERT_ISSUER_O = 5;					// 证书颁发者组织名(O)
var X509_CERT_ISSUER_OU = 6;				// 证书颁发者部门名(OU)
var X509_CERT_ISSUER_S = 7;					// 证书颁发者所在的省、自治区、直辖市(S)
var X509_CERT_ISSUER_CN = 8;				// 证书颁发者通用名称(CN)
var X509_CERT_ISSUER_L = 9;					// 证书颁发者所在的城市、地区(L)
var X509_CERT_ISSUER_E = 10;				// 证书颁发者Email
var X509_CERT_NOTBEFORE = 11;				// 证书有效期：起始日期
var X509_CERT_NOTAFTER = 12;				// 证书有效期：终止日期
var X509_CERT_SUBJECT_C = 13;				// 证书拥有者国家(C )
var X509_CERT_SUBJECT_O = 14;				// 证书拥有者组织名(O)
var X509_CERT_SUBJECT_OU = 15;				// 证书拥有者部门名(OU)
var X509_CERT_SUBJECT_S = 16;				// 证书拥有者所在的省、自治区、直辖市(S)
var X509_CERT_SUBJECT_CN = 17;				// 证书拥有者通用名称(CN)
var X509_CERT_SUBJECT_L = 18;				// 证书拥有者所在的城市、地区(L)
var X509_CERT_SUBJECT_E = 19;				// 证书拥有者Email
var X509_CERT_ISSUER_DN = 20;				// 证书颁发者DN
var X509_CERT_SUBJECT_DN = 21;				// 证书拥有者DN
var X509_CERT_DER_PUBKEY = 22;				// 证书公钥信息
var X509_CERT_EXT_CRLDISTRIBUTIONPO = 23;	// CRL发布点

// 河南省公共资源兼容解析项
var X509_CERT_IDENTIFY_NUM     =    1001;	// 身份证号
var X509_CERT_USCC             =    1002;	// 统一社会信用代码
var X509_CERT_COUNTRY          =    1003;	// 国家名称
var X509_CERT_PROVINCE         =    1004;	// 省名称
var X509_CERT_CITY             =    1005;	// 市名称
var X509_CERT_EMAIL            =    1006;	// 电子邮件
var X509_CERT_APPLICATIONNAME  =    1007;	// 项目应用名称
var X509_CERT_ENTERPRISENAME   =    1008;	// 企业名称/姓名

////////////////////////////////////////////////////

// 管理员key类型配置
var ks_provider = ""; // 介质
var ks_alg = ALGID_AUTO;    // 非对称算法，根据证书内容适配
var ks_path = "C:\\CONT\\?";   // 如果为软算法，对应路径 当前应不再使用RSA
var ks_hash_alg = ALGID_AUTO; // 自动适配算法，RSA时为SHA1, SM2时为SM3


function IsIE(){
	//判断是否为IE内核浏览器
	var u = window.navigator.userAgent.toLocaleLowerCase();
	var msie = /(msie) ([\d.]+)/;
	var chrome = /(chrome)\/([\d.]+)/;
	var firefox = /(firefox)\/([\d.]+)/;
	var safari = /(safari)\/([\d.]+)/;
	var opera = /(opera)\/([\d.]+)/;
	var ie11 = /(trident)\/([\d.]+)/;
	b = u.match(msie)||u.match(chrome)||u.match(firefox)||u.match(safari)||u.match(opera)||u.match(ie11);
	if(b[1] == "msie" || b[1] == 'trident'){
		return true;
	}else{
		return false;
	}
}

// UTCtime(yyMMdd[Zz]) 转化为北京时间 yyyyMMddHHmm
function UTCTime2BJTime(utctime){
    // 1. 判断输入数据长度，处理数据
    if (12 > utctime.length || 15 < utctime.length)
    {
        return "";
    }
    var targetTime = "";
    if (13 == utctime.length || 15 == utctime.length)
    {
        targetTime = utctime.slice(0, utctime.length-1);
    }
    // 2. 根据年数进行补充头两位
    // 根据长度判断是否补充
    if (12 == targetTime.length)
    {
        // 根据头两位判断补充19或者20
        var strPerfix = targetTime.slice(0, 2);
        var iYearNum = parseInt(strPerfix, 10);
        if (0 > iYearNum || 100 < iYearNum)
        {
            return "";
        }
        if (iYearNum < 70)
        {
            var tempTime = "20";
            targetTime = tempTime + targetTime;
        }
        else
        {
            var tempTime = "19";
            targetTime = tempTime + targetTime;
        }
    }
    // 3. 增加时区+8小时至北京时间
	var tm_year = parseInt(targetTime.slice(0,   4));
	var tm_mon  = parseInt(targetTime.slice(4,   6));
	var tm_mday = parseInt(targetTime.slice(6,   8));
	var tm_hour = parseInt(targetTime.slice(8,  10));
	var tm_min  = parseInt(targetTime.slice(10, 12));
	var tm_sec  = parseInt(targetTime.slice(12, 14));
    
    tm_hour += 8;
	var ghour = tm_hour;
	tm_hour %= 24;
	if (tm_hour != ghour)   // 如果增加时区前小时和增加后不一致说明跨日day+1，否则不用操作
	{
		tm_mday++;
		if (1 == tm_mon || 3 == tm_mon || 5 == tm_mon || 7 == tm_mon || 8 == tm_mon || 10 == tm_mon || 12 == tm_mon)
		{
			if (32 == tm_mday)
			{
				tm_mon++;
				tm_mon %= 12;
				tm_mday = 1;
			}
		}
		else if (2 == tm_mon)
		{
			if ((0 == tm_year % 4 && 0 != tm_year % 100) || (0 == tm_year % 400))
			{
				if (30 == tm_mday)
				{
					tm_mon++;
					tm_mday = 1;
				}
			}
			else
			{
				if (29 == tm_mday)
				{
					tm_mon++;
					tm_mday = 1;
				}
			}
		}
		else
		{
			if (31 == tm_mday)
			{
				tm_mon++;
				tm_mon %= 12;
				tm_mday = 1;
			}
		}
	}
	// 4. 转化int to string
	var str_year = tm_year + "";
	var str_mon  = tm_mon  + "";
	var str_mday = tm_mday + "";
	var str_hour = tm_hour + "";
	var str_min  = tm_min  + "";
	var str_sec  = tm_sec  + "";
	if (1 == str_mon.length)
	{
	    str_mon = "0" + str_mon;
	}
	if (1 == str_mday.length)
	{
	    str_mday = "0" + str_mday;
	}
	if (1 == str_hour.length)
	{
	    str_hour = "0" + str_hour;
	}
	if (1 == str_min.length)
	{
	    str_min = "0" + str_min;
	}
	if (1 == str_sec.length)
	{
	    str_sec = "0" + str_sec;
	}
    // 5. 合成字符串
    return str_year + str_mon + str_mday + str_hour + str_min;
}

/**
 * 枚举支持的provider
 * provider: select ID
 */
function EnumProvider(provider){
       while(provider.length > 0){
		provider.remove(0);
	}
	
	var elem3 = document.createElement("option");
        elem3.value = "GGZY";
        elem3.text = "自动识别";
        provider.add(elem3);
	 

	if(provider.length > 0){
		provider.selectedIndex = 0;
	}
}

/**
* 获取插KeyVid
*/
function GetDeviceVid() {
    var result = "";
    if(IsIE()){
        result = SecCtrl.KS_GetDeviceVid();
        if(SecCtrl.KS_GetLastErrorCode() != 0){
    		alert(SecCtrl.KS_GetLastErrorMsg());
    	}
        return result;
    }else{
    	result=KS_GetDeviceVids();
    	return result;
    }
}
//获得硬件介质号
function GetDeviceSerialNumber(){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GetAllDeviceSerialNumber();
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_GetAllDeviceSerialNumbers();
		return result;
    }
}
/**
 * 初始化函数，设置相关初始值
 * p_provider: 算法提供者
 * p_alg: 非对称算法，1-RSA1024, 2-RSA2048, 3-ECC
 * p_path: 路径
 */
//设置算法提供者
function init(p_provider, p_alg, p_path){
	var result = "";
    if(p_provider != null && p_provider != ""){
    	ks_provider = p_provider;
    }
    if(p_alg != null && p_alg != ""){
    	ks_alg = p_alg;
    }
    if(p_path != null && p_path != ""){
    	ks_path = p_path;
    }
    if(IsIE()){
    var lRet = SecCtrl.KS_SetProv(ks_provider, ks_alg, ks_path);
    if(lRet != 0){
	alert(SecCtrl.KS_GetLastErrorMsg());
	
    }
	result=lRet;
	return result;
    }else{
    	result=KS_SetProvs(ks_provider,ks_alg,ks_path);
    	return result;
    }
}

/**
 * 获取控件版本
 */
function GetVersion(){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GetVersion();
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_GetVersions();
		return result;
    }
}



/**
 * 获取BASE64编码证书
 * type: 1、加密证书，2、签名证书
 */
function GetCert(type){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GetCert(type);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		
		result=KS_GetCerts(type);
		return result;
	}
}
/**
 * 获取证书信息
 * cert: Base64编码证书
 * item: 解析项。
 * 1、证书版本；2、证书序列号；3、证书签名算法标识；4、证书颁发者国家(C); 5、证书颁发者组织名(O);
 * 6、证书颁发者部门名(OU); 7、证书颁发者所在的省、自治区、直辖市(S); 8、证书颁发者通用名称(CN); 9、证书颁发者所在的城市、地区(L);
 * 10、证书颁发者Email; 11、证书有效期：起始日期; 12、证书有效期：终止日期; 13、证书拥有者国家(C ); 14、证书拥有者组织名(O);
 * 15、证书拥有者部门名(OU); 16、证书拥有者所在的省、自治区、直辖市(S); 17、证书拥有者通用名称(CN); 18、证书拥有者所在的城市、地区(L);
 * 19、证书拥有者Email; 20、证书颁发者DN; 21、证书拥有者DN; 22、证书公钥信息; 23、CRL发布点.
 */
//解析证书
function GetCertInfo(cert, item){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GetCertInfo(cert, item);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		
		result=KS_GetCertInfos(cert, item);
		return result;
	}
}

/**
 * 获取证书扩展信息
 * cert: Base64编码证书
 * oid: oid值
 */
function GetCertInfoByOid(cert, oid){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GetCertInfoByOid(cert, oid);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_GetCertInfoByOids(cert, oid);
		return result;
	}
}

/**
 * 生成随机数
 * len: 随机数长度
 */
function GenRandom(len){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GenRandom(len);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_GenRandoms(len);
		return result;
	}
}

/**
 * 数据摘要
 * indata: 输入数据
 * hashAlg:摘要算法。1-SHA1, 2-SHA256, 3-SHA512, 4-MD5, 5-MD4
 */
function HashData(indata, hashAlg){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_HashData(indata, 1);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_HashDatas(indata,hashAlg);
		return result;
	}
}

/**
 * 数据签名
 * indata：明文数据
 * hashAlg: 1-SHA1, 2-SHA256, 3-SHA512, 4-MD5, 5-MD4, 6-SM3
 * return：签名数据
 */
function SignData(indata, hashAlg){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_SignData(indata, hashAlg);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_SignDatas(indata, hashAlg);
		return result;
	}

}

/**
 * 数据验签
 * indata：明文数据
 * signdata：签名数据
 * cert: 证书
 * hashAlg: 1-SHA1, 2-SHA256, 3-SHA512, 4-MD5, 5-MD4, 6-SM3
 * return：成功=true，失败=false
 */
function VerifySignData(indata, signdata, cert, hashAlg){
        var result = "";
    if(IsIE()){
	result = SecCtrl.KS_VerifySignData(indata, signdata, cert, hashAlg);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
    }else{
		result=KS_VerifySignDatas(indata, signdata, cert, hashAlg);
		return result;
    }
}

/**
 * 数据签名P7
 * indata：明文数据
 * hashAlg: 1-SHA1, 2-SHA256, 3-SHA512, 4-MD5, 5-MD4, 6-SM3
 * return：签名数据
 */
function SignDataByP7(indata, hashAlg){
	var result = "";
	if(IsIE()){
	SecCtrl.KS_SetParam("signtype", "pksc7");
	result = SecCtrl.KS_SignData(indata, hashAlg);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	 }else{
			KS_SetParams("signtype", "pksc7");
			return KS_SignDatas(indata, hashAlg);
	 }
}

//对称加密
function SymmEncrypt(indata, key, symmAlg){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_SymmEncrypt(indata, key, symmAlg);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_SymmEncrypts(indata, key, symmAlg);
		return result;
	}
}
//对称解密
function SymmDecrypt(indata, key, symmAlg){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_SymmDecrypt(indata, key, symmAlg);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_SymmDecrypts(indata, key, symmAlg);
		return result;
	}
	
}

//组数字信封
function MakeEnvelope(indata, enccert){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_MakeEnvelope(indata, enccert);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		//alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_MakeEnvelopes(indata, enccert);
		return result;
	}
}

//解数字信封
function OpenEnvelope(envelope){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_OpenEnvelope(envelope);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		//alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_OpenEnvelops(envelope);
		return result;
	}
}
/**
 * 数据验签P7
 * p7data：P7数据
 * hashAlg: 1-SHA1, 2-SHA256, 3-SHA512, 4-MD5, 5-MD4, 6-SM3
 * return：成功=true，失败=false
 */
function VerifyP7SignData(p7data){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_VerifyP7SignData(p7data);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_VerifyP7SignDatas(p7data);
		return result;
	}
}






function GetGGZYSeal(extend){
    var result = "";
    if(IsIE()){
    result = SecCtrl.KS_GGZYGainSeal(extend);
    if(SecCtrl.KS_GetLastErrorCode() != 0){
        alert(SecCtrl.KS_GetLastErrorMsg());
    }
    return result;
    }else{
		result=KS_GGZYGainSeals(extend);
		return result;
	}

}
// 对hash签名
function SignHashData(indata, hashalg){
    var result = "";
    if(IsIE()){
        result = SecCtrl.KS_SignHashData(indata, hashalg);
        if(SecCtrl.KS_GetLastErrorCode() != 0){
            alert(SecCtrl.KS_GetLastErrorMsg());
        }
        return result;
    }else{
        result=KS_SignHashDatas(indata, hashalg);
        return result;
    }
}

// 设置参数
function KS_SetParam(str_paramname,str_path){
    var result = "";
    if(IsIE()){
        result = SecCtrl.KS_SetParam(str_paramname,str_path);
        if(SecCtrl.KS_GetLastErrorCode() != 0){
            alert(SecCtrl.KS_GetLastErrorMsg());
        }
        return result;
    }else{
        result=KS_SetParams(str_paramname,str_path);
        return result;
    }
}

//解数字信封
function GGZYCompatibleOpenEnvelope(envelope){
	var result = "";
	if(IsIE()){
	result = SecCtrl.KS_GGZYCompatibleOpenEnvelope(envelope);
	if(SecCtrl.KS_GetLastErrorCode() != 0){
		//alert(SecCtrl.KS_GetLastErrorMsg());
	}
	return result;
	}else{
		result=KS_GGZYCompatibleOpenEnvelopes(envelope);
		return result;
	}
}